package net.ming616.nlp.base.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;

/**
 * 
 * @author liuxiaoming
 * 
 */
@MappedSuperclass
public class BaseTreeModel<T extends BaseTreeModel<?>> extends BaseModel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3614785534038940700L;

	@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
	@OrderBy("sort asc")
	protected List<T> children;
	@Column(name = "LEAF")
	protected Boolean leaf = Boolean.TRUE;

	/**
	 */
	@Column(name = "LEVEL")
	protected Long level = Long.valueOf(0);

	/**
	 */
	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "PARENTID")
	protected T parent;

	public void addChild(T child) {
		if (this.children == null) {
			this.children = new ArrayList<T>();
		}
		this.children.add(child);
	}

	public List<T> getChildren() {
		return children;
	}

	public Long getLevel() {
		if (null == this.parent) {
			this.level = Long.valueOf(0);
		} else {
			this.level = this.parent.getLevel() + 1;
		}
		return level;
	}

	public T getParent() {
		return parent;
	}

	public Boolean isLeaf() {
		if (this.children != null && this.children.size() > 0) {
			this.leaf = true;
		} else {
			this.leaf = false;
		}
		return leaf;
	}

	public void setChildren(List<T> children) {
		this.children = children;
	}

	public void setLeaf(Boolean leaf) {
		this.leaf = leaf;
	}

	public void setLevel(Long level) {
		this.level = level;
	}

	public void setParent(T parent) {
		this.parent = parent;
	}
}
